package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.web.service.impl.TaskScheduler2;
import org.dromara.web.service.jobStatusService;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定时任务调度Controller
 *
 * @author Zou
 */
@Validated
@RestController
@SaIgnore
@RequiredArgsConstructor
@RequestMapping("/jobTask")
@Slf4j
public class TaskSchedulerController {
    private final TaskScheduler2 taskScheduler;
    private final jobStatusService jobStatusService;

    /**
     * 停止指定任务
     *
     * @param serviceName   serviceName
     * @param serviceMethod serviceMethod
     * @return R
     */
    @SaCheckPermission("job:job:stopOne")
    @DeleteMapping("/stop/{serviceName}/{serviceMethod}")
    public R<String> stopTask(@PathVariable String serviceName, @PathVariable String serviceMethod) {
        try {
            // 1. 停止任务
            taskScheduler.stopScheduledTask(serviceName, serviceMethod);
            // 2. 获取对应的 methodName
            String methodName = jobStatusService.getCurrentMethodName(serviceName, serviceMethod);
            if (StringUtils.isBlank(methodName)) {
                log.warn("未找到 serviceName={}, serviceMethod={} 对应的 methodName", serviceName, serviceMethod);
                return R.fail("任务不存在或已停止");
            }
            // 3. 递减状态
            jobStatusService.decrementStatus(methodName);
            // 4. 清除本地缓存记录
            jobStatusService.removeMethodNameFromCache(serviceName, serviceMethod);
            return R.ok("任务已停止：serviceName=" + serviceName + ", serviceMethod=" + serviceMethod);
        } catch (Exception e) {
            log.error("停止任务失败", e);
            return R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }

    /**
     * 停止所有任务
     *
     * @return R
     */
    @SaCheckPermission("job:job:stopAll")
    @DeleteMapping("/stopAll")
    public R<String> stopAllTasks() {
        try {
            taskScheduler.stopAllScheduledTasks(); // 调用TaskScheduler2的停止所有任务的方法
            jobStatusService.resetAllMethodStatus();
            return R.ok("所有定时任务已停止");
        } catch (Exception e) {
            log.error("停止所有任务失败", e);
            return R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }
}
